package com.fjec.common.zk;

import com.fjec.common.Const;
import com.fjec.common.util.NumberUtil;
import com.google.common.base.Strings;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.TimeUnit;

public class ZkShopNumHelper {

    private CuratorFramework client;

    public ZkShopNumHelper(CuratorFramework client) {
        this.client = client;
    }

    public boolean existsAndCreate(String path) throws Exception {
        boolean ret = false;
        Stat stat = this.client.checkExists().forPath(path);
        if (stat == null) {
            this.client.create()
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.PERSISTENT)
                    .forPath(path);
            ret = true;
        }
        return ret;
    }

    public String getSequence(String path) throws Exception {
        String zkPath = Const.ZK_SHOP_NUM_SEQ_ROOT + "/" + path;
        InterProcessMutex lock = new InterProcessMutex(client, zkPath);
        boolean retry = true;
        byte[] newData = null;
        do {
            if (lock.acquire(1000, TimeUnit.MILLISECONDS)) {
                byte[] oldData = client.getData().forPath(zkPath);
                String strTmp = new String(oldData);
                if (Strings.isNullOrEmpty(strTmp)) {
                    strTmp = Const.ZK_SHOP_NUM_SEQ_INIT_VAL;
                }
                long tmp = Integer.parseInt(strTmp);
                tmp = tmp + 1;
                tmp = NumberUtil.giveUpNum(tmp, 4);
                strTmp = String.valueOf(tmp);
                newData = strTmp.getBytes();
                client.setData().forPath(path, newData);
                retry = false;
            }
        } while (retry);
        return String.format("%06d", newData);
    }

}
